package org.shellex.javame.utility;

import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Alert;
 
/**
 * @author Favo
 * Preferences - Java - Code Style - Code Templates
 */
public abstract class BackgroundTask extends Thread {
 
    ProgressObserver poUI;
 
    protected Displayable preScreen;
 
    protected boolean needAlert;
 
    protected Alert alertScreen;
 
    private Display display;
 
    public BackgroundTask(ProgressObserver poUI, Displayable pre,
           Display display) {
       this.poUI = poUI;
       this.preScreen = pre;
       this.display = display;
       this.needAlert = false;
    }
 
    public void run() {
       try {
           runTask();
       } catch (Exception e) {
//           Alert al = new Alert("undefine exception",
//        		   e.getMessage(), null,
//                               AlertType.ALARM);
//           al.setTimeout(Alert.FOREVER);
//           display.setCurrent(al);
    	   e.printStackTrace();
       } finally {
           if (poUI.isStoppable()) {
              if (poUI.isStopped()) {//如果用户中断了程序
                  if (needAlert) {
                     display.setCurrent(alertScreen, preScreen);
                  } else {
                     display.setCurrent(preScreen);
                  }
              }
           }
           poUI.exit();
       }
    }
 
    /*
     * 如果任务可中断,查看pgUI.isStopped().并尽快退出此方法;
* 如果任务需要更新进度栏，调用pgUI.updateProgress(“进度提示”).
* 习惯上此方法的最后手动调用taskComplete()以防止用户在任务接近
* 完成时取消
     */
    public abstract void runTask();
 
    /**
* 这是一个偷懒的办法,当你构造好BackgroundTask对象后，直接调用这个方法， *可以帮助你初始化进度UI,并显示出来。之后启动你的任务线程
    */
    public static void runWithProgressGauge(BackgroundTask btask, String title,
           String prompt, boolean stoppable, Display display) {
       ProgressObserver po = btask.getProgressObserver();
       po.reset();
       po.setStoppable(stoppable);
       po.setTitle(title);
       po.setPrompt(prompt);
       po.show(display);
       btask.start();
    }
 
    public ProgressObserver getProgressObserver() {
       return poUI;
    }
   
    public void taskComplete(){
       getProgressObserver().setStopped(false);
    }
}
